package com.o2opays.wechat.job;

import com.o2opays.wechat.pojo.AccessToken;
import com.o2opays.wechat.pojo.Ticket;
import com.o2opays.wechat.pojo.WeChatContent;
import com.o2opays.wechat.pojo.WeChatFinalValue;
import com.o2opays.wechat.tool.HttpClientUtil;
import com.o2opays.wechat.tool.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;

/**
 * Created by tugou on 2017/12/2.
 */
@Configuration
@EnableScheduling
public class WeChatInitJob {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${wechat_appid}")
    private String wechat_appid;
    @Value("${wechat_token}")
    private String wechat_token;
    @Value("${wechat_base_url}")
    private String wechat_base_url;
    @Value("${wechat_appsecret}")
    private String wechat_appsecret;

    @Scheduled(fixedRate = 1000 * 60 * 60,initialDelay = 100) // 每20秒执行一次
    public void tokenInit() {
        WeChatContent weChatConten = WeChatContent.getInstance();
        weChatConten.setAppId(wechat_appid);
        weChatConten.setAppSecurt(wechat_appsecret);
        weChatConten.setToken(wechat_token);
        weChatConten.setBaseUrl(wechat_base_url);
        String url = WeChatFinalValue.ACCESS_TOKEN_URL;
        url = url.replaceAll("APPID", wechat_appid);
        url = url.replaceAll("APPSECRET", wechat_appsecret);
        try {
            String content = HttpClientUtil.doGet(url);
            System.out.println("获取微信token:"+content);
            logger.info("获取微信token:"+content+"||"+new Date());
            AccessToken token = JsonUtil.toObject(content, AccessToken.class);
            weChatConten.setAccessToken(token);
            if(token.getAccess_token() != null && token.getExpires_in() != null){
                String jsUrl = WeChatFinalValue.ACCESS_JS_TOKEN_URL;
                jsUrl = jsUrl.replace("ACCESS_TOKEN", WeChatContent.getInstance().getAccessToken().getAccess_token());
                String jsContent = HttpClientUtil.doGet(jsUrl);
                Ticket jsToken = JsonUtil.toObject(jsContent, Ticket.class);
                weChatConten.setJsTicket(jsToken);
                logger.info("获取微信js-token:"+jsContent);
                logger.info("获取微信js-token:"+content+"||"+new Date());
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
        }
    }
}
